package com.lf.web.service.system.role;

import com.lf.data.Cluster;
import com.lf.data.ClusterUtil;
import com.lf.data.Validate;
import com.lf.data.file.Limit;
import com.lf.web.service.ServiceSupport;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class RoleDetailService extends ServiceSupport {

    private static final Logger LOGGER = Logger.getLogger(RoleDetailService.class);
    private RoleDAO roledao;

    public void setRoledao(RoleDAO roledao) {
        this.roledao = roledao;
    }

    public String execute() {
        String id = form.getString("id");
        LOGGER.debug("id=" + id);
        if (Validate.check(Validate.OBJECTID, id)) {
            Cluster role = roledao.findById(id);
            if (role.isEmpty()) {
                LOGGER.error("所查看的角色不存在");
                error(404);
                return NONE;
            }
            initLimit(role);
            context.put("role", role);
            context.put("check", ClusterUtil.getCheck(Role.class));
            return "detail";
        } else {
            error(404);
            LOGGER.error("错误参数：id=" + id);
            return NONE;
        }
    }

    private void initLimit(Cluster role) {
        Map<String, Object> limit = role.getMap(Role.LIMIT);
        Limit limitLoad = new Limit();
        if (limitLoad.load()) {
            List<Cluster> limits = limitLoad.getLimit();
            List<Cluster> limitModules = new ArrayList<>();
            for (Cluster module : limits) {
                boolean contain = false;
                for (Object object : module.getList("action")) {
                    Map<String, Object> action = (Map<String, Object>) object;
                    if (limit.containsKey(action.get("key"))) {
                        contain = true;
                        break;
                    }
                }
                if (contain) {
                    limitModules.add(module);
                }
            }
            context.put("limitConfig", limitModules);
        }
    }

}
